package com.dc.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

@Component
public class ServerChannelInitializer extends ChannelInitializerAbstract {

    @Resource
    ServerChannelAbstract serverChannelAbstract;

    @Override
    protected void initChannel(SocketChannel socketChannel) {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //IdleStateHandler心跳机制,如果超时触发Handle中userEventTrigger()方法
        pipeline.addLast("idleStateHandler",
                new IdleStateHandler(15, 0, 0, TimeUnit.MINUTES));
        //字符串编解码器
//        ByteBuf buf = Unpooled.copiedBuffer("_$".getBytes());
//        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024*1024, buf));
//        socketChannel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
        //自定义Handler
        pipeline.addLast("serverChannelHandler", serverChannelAbstract);
    }
}
